#include "blockio.h"


#ifdef BLOCKIO_DEBUGB
#define dbg_print(fmt, ...)			\
	do{								\
		printk("LED: ");			\
		printk(fmt, ##__VA_ARGS__);	\
		printk("\r\n");				\
	}while(0)
#else
#define dbg_print(fmt, ...)
#endif

DEFINE_KFIFO(gfifo, char, 32);
//定义并初始化等待队列
DECLARE_WAIT_QUEUE_HEAD(read_queue);
DECLARE_WAIT_QUEUE_HEAD(write_queue);

//打开设备
static int blockio_open(struct inode *inode, struct file *file)
{
	return 0;
}

//释放设备
static int blockio_release(struct inode *inode, struct file *file)
{
	return 0;
}

//读设备
static ssize_t blockio_read(struct file *file, char __user *buf, size_t len, loff_t *pos)
{
	unsigned int copied;

	if(kfifo_is_empty(&gfifo))
	{
		dbg_print("fifo is empty\r\n");

		//以非阻塞式打开，直接返回-EAGAIN
		if(file->f_flags & O_NONBLOCK)
			return -EAGAIN;

		//挂起当前进程到等待队列，能被信号唤醒
		if(wait_event_interruptible_exclusive(read_queue, !kfifo_is_empty(&gfifo)))
		{
			//返回-ERESTARTSYS，表示被信号唤醒
			return -ERESTARTSYS;
		}
	}

	//将FIFO中的数据读取到应用层
	if(kfifo_to_user(&gfifo, buf, len, &copied) != 0)
	{
		dbg_print("Bad address\r\n");
		return -EFAULT;
	}

	//如果可以写入则唤醒写进程
	if(!kfifo_is_full(&gfifo))
		wake_up_interruptible(&write_queue);

	return copied;
}

//写设备
static ssize_t blockio_write(struct file *file, const char __user *buf, size_t len, loff_t *pos)
{
	unsigned int copied;

	if(kfifo_is_full(&gfifo))
	{
		dbg_print("fifo is full\r\n");

		//以非阻塞式打开，直接返回-EAGAIN
		if(file->f_flags & O_NONBLOCK)
			return -EAGAIN;

		//挂起当前进程到等待队列，能被信号唤醒
		if(wait_event_interruptible_exclusive(write_queue, !kfifo_is_full(&gfifo)))
		{
			//返回-ERESTARTSYS，表示被信号唤醒
			return -ERESTARTSYS;
		}
			
	}

	//将应用层的数据写入FIFO
	if(kfifo_from_user(&gfifo, buf, len, &copied) != 0)
	{
		dbg_print("Bad address\r\n");
		return -EFAULT;
	}

	//如果有数据可读则唤醒读进程
	if(!kfifo_is_empty(&gfifo))
		wake_up_interruptible(&read_queue);

	return copied;
}

static struct file_operations ops = {
	.owner = THIS_MODULE,
	.write = blockio_write,
	.read = blockio_read,
	.open = blockio_open,
	.release = blockio_release,
};

static struct miscdevice blockio_misc = {
	.name = BLOCKIO_NAME,
	.minor = BLOCKIO_MINOR,
	.fops = &ops,
};

static int __init blockio_init(void)
{
	int err = 0;

	printk("blockio memory init,1\r\n");

	//注册混杂设备
	err = misc_register(&blockio_misc);
	if(err != 0)
	{
		dbg_print("register misc failed\r\n");
		return err;
	}

	return 0;
}

static void __exit blockio_exit(void)
{
	printk("blockio memory exit\r\n");

	//注销混杂设备
	misc_deregister(&blockio_misc);
}

module_init(blockio_init);
module_exit(blockio_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("lf");
MODULE_DESCRIPTION("blockio");
